package com.sep.team4.data;

import java.util.ArrayList;

/**
 * Instances of this class represent a test that has been been made by the user.
 * It can be used to get information about the test including the grades the
 * user received for the test.
 * 
 * @author Mitchell
 * 
 */
public class Test {

	// The name of the test.
	private String name;
	// The weight this test has.
	private int weight;
	// The database ID of this test.
	private int testID;
	// The lowest allowed grade for this test.
	private double lowestAllowedGrade;
	// All the grades the user received for this test.
	private ArrayList<Grade> grades;

	/**
	 * The constructor.
	 * 
	 * @param name
	 *            The name of the test.
	 * @param weight
	 *            The weight of the test.
	 * @param testID
	 *            The database ID of the test.
	 * @param lowestAllowedGrade
	 *            The lowest allowed grade of the test.
	 */
	public Test(String name, int weight, int testID, double lowestAllowedGrade) {
		this.name = name;
		this.weight = weight;
		this.testID = testID;
		this.lowestAllowedGrade = lowestAllowedGrade;
		grades = null;
	}

	public Test() {
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	public void setTestID(int testID) {
		this.testID = testID;
	}

	public void setLowestAllowedGrade(double lowestAllowedGrade) {
		this.lowestAllowedGrade = lowestAllowedGrade;
	}

	public void setGrades(ArrayList<Grade> grades) {
		this.grades = grades;
	}

	/**
	 * Returns the name of the test.
	 * 
	 * @return The name of the test.
	 */
	public String getName() {
		return name;
	}

	/**
	 * Returns the weight of the test.
	 * 
	 * @return The weight of the test.
	 */
	public int getWeight() {
		return weight;
	}

	/**
	 * Returns the lowest allowed grade for the test.
	 * 
	 * @return The lowest allowed grade for the test.
	 */
	public double getLowestAllowedGrade() {
		return lowestAllowedGrade;
	}

	/**
	 * Returns an ArrayList containing all the grades the user received for the
	 * test from the database.
	 * 
	 * @return All the grades that belong to the test.
	 */
	public ArrayList<Grade> getGrades() {
		if (grades == null) {
			grades = DatabaseManager.getInstance().getGrades(testID);
		}
		return grades;
	}

	public int getTestID() {
		return testID;
	}

	public double getWeightIfEarned() {
		double weight = 0;
		double gradeForTest = 0;
		int heighestAttempt = 0;
		try {
			for (Grade grade : getGrades()) {
				if (grade.getAttempt() > heighestAttempt) {
					gradeForTest = grade.getValue();
					heighestAttempt = grade.getAttempt();
				}
			}
			if (gradeForTest >= lowestAllowedGrade) {
				weight = this.weight;
			}
		} catch (Exception e) {
			weight = this.weight;
		}
		return weight;
	}

}
